//
//  ZLFileManagerExtension.swift
//  ZLExtension
//
//  Created by 科大 on 2024/12/23.
//

import Foundation

/// 文件保存配置
public struct ZLFileConfig {
    /// 数据
    var data: Data!
    /// 路径
    var path: URL!
    
    /// 初始化
    init(data: Data!, path: URL!) {
        self.data = data
        self.path = path
    }
}

public struct ZLImageConfig {
    /// 数据
    var image: UIImage!
    /// 路径
    var path: URL!
    /// 压缩路径
    var thumbnailPath: URL!
    
    /// 初始化
    init(image: UIImage!, path: URL!, thumbnailPath: URL!) {
        self.image = image
        self.path = path
        self.thumbnailPath = thumbnailPath
    }
}

public extension FileManager {
    /// 获取沙盒Document路径
    class func zl_documentPath() -> URL {
        let url = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
        return url
    }
    /// 获取沙盒Library路径
    class func zl_libraryPath() -> URL {
        let url = FileManager.default.urls(for: .libraryDirectory, in: .userDomainMask).first!
        return url
    }
    /// 获取沙盒Caches路径
    class func zl_cachesPath() -> URL {
        let url = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!
        return url
    }
    /// 获取沙盒Preferences路径
    class func zl_preferencesPath() -> URL {
        let url = FileManager.default.urls(for: .libraryDirectory, in: .userDomainMask).first!.appendingPathComponent("Preferences")
        return url
    }
    /// 获取沙盒tmp路径
    class func zl_tmpPath() -> URL {
        let url = FileManager.default.temporaryDirectory
        return url
    }
}

public extension FileManager {
    /// 文件夹是否存在
    class func zl_exists(path: URL) -> Bool {
        return FileManager.default.fileExists(atPath: path.relativePath)
    }
    /// 创建文件夹
    @discardableResult
    class func zl_createDirectory(path: URL) -> Bool {
        if !FileManager.default.fileExists(atPath: path.relativePath) {
            do {
                try FileManager.default.createDirectory(atPath: path.relativePath, withIntermediateDirectories: true, attributes: nil)
                return true
            } catch let error {
                debugPrint("zl_createDirectory error: \(error)")
                return false
            }
        }
        return true
    }
    
    /// 保存文件
    /// - Parameters:
    ///   - data: 数据
    ///   - path: 路径
    /// - Returns: 结果
    @discardableResult
    class func zl_save(name: String, data: Data, path: URL, autoCreateFolder: Bool = true) -> Bool {
        if autoCreateFolder {
            if self.zl_exists(path: path) == false {
                if self.zl_createDirectory(path: path) == false {
                    return false
                }
            }
        }
        do {
            let savePath = path.appendingPathComponent(name)
            try data.write(to: savePath)
            return true
        } catch {
            print("zl_save error: \(error.localizedDescription)")
            return false
        }
    }
    
    /// 批量保存图片到本地
    /// - Parameters:
    ///   - imgs: 图片数组
    ///   - folder: 文件夹
    ///   - isThumbnail: 是否存储缩略图
    ///   - completion: 完成回调
    class func zl_saveImgs(configs: [ZLImageConfig], completion: @escaping () -> Void) {
        DispatchQueue.global(qos: .background).async {
            configs.forEach { config in
                do {
                    let data = config.image.jpegData(compressionQuality: 1.0)
                    let thumbnailData = config.image.jpegData(compressionQuality: 0.2)
                    try data?.write(to: config.path)
                    try thumbnailData?.write(to: config.path)
                } catch {
                    print("zl_saveFiles path: \(config.path.relativePath) error: \(error.localizedDescription)")
                }
            }
            DispatchQueue.main.async {
                completion()
            }
        }
    }
    
    /// 批量保存文件
    /// - Parameters:
    ///   - datas: 数据数组
    ///   - folder: 目标文件夹
    ///   - suffix: 后缀
    ///   - completion: 完成回调 文件名
    class func zl_saveFilesByUUID(datas: [Data], folder: URL, suffix: String, completion: @escaping ([String]) -> Void) {
        var configs: [ZLFileConfig] = []
        var paths: [String] = []
        datas.forEach { data in
            let suffixString = suffix.first == "." ? suffix : ".\(suffix)"
            let name = UUID().uuidString.appending(suffixString)
            let path = folder.appendingPathComponent(name)
            configs.append(ZLFileConfig(data: data, path: path))
            paths.append(name)
        }
        self.zl_saveFiles(configs: configs) {
            completion(paths)
        }
    }
    
    /// 批量保存文件
    /// - Parameters:
    ///   - configs: 保存参数配置
    ///   - completion: 完成回调
    class func zl_saveFiles(configs: [ZLFileConfig], completion: @escaping () -> Void) {
        DispatchQueue.global(qos: .background).async {
            configs.forEach { config in
                do {
                    try config.data.write(to: config.path)
                } catch {
                    print("zl_saveFiles path: \(config.path.relativePath) error: \(error.localizedDescription)")
                }
            }
            DispatchQueue.main.async {
                completion()
            }
        }
    }
    
    /// 删除文件/文件夹
    class func zl_delete(path: URL) -> Bool {
        if !FileManager.zl_exists(path: path) {
            return true
        }
        do {
            try FileManager.default.removeItem(atPath: path.relativePath)
            return true
        } catch {
            return false
        }
    }
}
